//表单注册 之后判断
const express = require('express');
let router = express.Router();
const fs = require('fs');
const path = require('path');
const timeStamp = require('time-stamp');//引入时间模块
let svgCaptcha = require('svg-captcha');
let Db = require('../utils/db完整');//引入数据库
let uuid=require('uuid');
let md5=require('md5');


//生成验证码
let registerCode = '';//验证码文字定义全局变量
router.get('/getsvgP', (req, res) => {
  let svg = svgCaptcha.create({
    size: 4,
    color: false,
    background: "#eee",
    ignoreChars: "1Il0Oo",//忽略一些字符，
    noise: 0
  })
  registerCode = svg.text;
  res.type("svg")// 把文件类型设置为svg
  res.send(svg.data);
});

router.post('/register', async (req, res, next) => {
  let { tel, pass, pass2 } = req.body;
  console.log(registerCode, 222);
  if (!tel || !pass || !pass2) {
    next("用户名或密码为空")
    return
  };
  if (pass != pass2) {
    next("两次输入的密码不一样")
    return;
  };
  // if (registerCode.toLowerCase() != captcha.toLowerCase()) {
  //   next('验证码输入有误');
  //   return;
  // }
  /*-----------转换成async await风格,且函数封装----------------
  在上面路由中的箭头函数 上设置async */
  let sqlP1 = `SELECT * FROM e_member  WHERE username='${tel}'`;
  let resData = await Db(sqlP1);

  let [err, results] = resData;  //解构
  console.log(err, 111); console.log(results, 222);
  if (err) {
    next([err, '服务器故障 稍后再试']);
    return;
  };
  if (results.length > 0) {
    next('用户名已被注册');
    return;
  };
  //results.length==0--->可以注册 
  let mid=uuid.v4();
  //console.log(mid,'uuid');//0a1fbb4f-337e-42f0-a681-5dd9c2cbad20
  // return;
  let sqlP2 = `INSERT INTO e_member (mid,username,password,createdate) values ('${mid}','${tel}','${md5(md5(pass))}','${Date.now()}') `;
  let resData1 = await Db(sqlP2);
  let [err1, results1] = resData1;  //解构
  console.log(err1, 333); console.log(results1, 444);
  if (err1) {
    next(err);
    return;
  };
  res.send({
    status: 200,
    msg: '注册成功',
  })
})
module.exports = router;



